package com.example.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.bean.Order;
import com.example.order.feign.ProductFeignClient;
import com.example.order.service.OrderService;
import com.example.product.Bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductFeignClient productFeignClient;
    // 只有快速失败支持流控模式的设置
    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = productFeignClient.getProductById(productId, "my token");
        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setNickName("ddd");
        order.setAddress("南京");
        order.setProductList(Arrays.asList(product));

        /*try {
            SphU.entry("资源名");
        } catch (BlockException e) {
            //编码处理
        }*/

        return order;
    }

    //兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(userId);
        order.setTotalAmount(new BigDecimal("0"));
        order.setNickName("未知用户");
        order.setAddress("异常信息:" + e.getClass());
        return order;
    }

    // 基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {

        String url = "http://service-product/product/" + productId;
        log.info("远程请求:{}", url);
        //2. 给远程发送请求 service-product 会被动态替换
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    // 完成负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        //1.获取到商品服务所在机器IP+PORT
        ServiceInstance instance  = loadBalancerClient.choose("service-product");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求:{}", url);
        //2. 给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    private Product getProductFromRemote(Long productId) {
        //1.获取到商品服务所在机器IP+PORT
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求:{}", url);
        //2. 给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

}
